package com.hxzy.common.web.controller;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.vo.PageVO;
import com.hxzy.common.vo.R;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.List;


/**
 * 通用控制器
 */
public class BaseController {


    protected R toR(int row){
        return  row>0? R.ok():  R.build(AckCode.FAIL);
    }

    protected  R toR(boolean result){
        return  result? R.ok():  R.build(AckCode.FAIL);
    }

    /**
     * 第页第三步，把Mybatis返回的结果IPage转换自定义的对象
     * @param page
     * @return
     */
    protected R pageToPageVO(IPage page) {
        PageVO pageVo = new PageVO();
        pageVo.setTotal(page.getTotal());
        pageVo.setRows(page.getRecords());
        return R.okHasData(pageVo);
    }

    /**
     * 把list变为分页的输出结果
     * @param list
     * @return
     */
    protected R listToPageVO(List list) {
        PageVO pageVo = new PageVO();
        pageVo.setTotal(0L);
        pageVo.setRows(list);
        return R.okHasData(pageVo);
    }



    protected <T> void writeExcel(HttpServletResponse response, String excelName, Class<T> tClass, List<T> data) throws IOException {

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String chinaFileName=excelName+"_"+ UUID.fastUUID().toString()+".xlsx";

        String fileName = URLEncoder.encode(chinaFileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename="+ fileName );

        //文件下载
        EasyExcel.write(response.getOutputStream(), tClass).sheet(excelName).doWrite(data );
    }
}
